<template>
	<view :id="templateId" v-if="loaded" class="container">
		<!-- 订单类型选择（到店，快递） -->
		<view 
			class="zz-ordertype-select zz-mt24">
			<!-- slider -->
			<view 
				class="slider"
				:style="[{'background-color':`${themeStyles.mainColor}`},{'border-color':`${themeStyles.mainColor}`},{'transform':`translateX(${orderTypeActive*246}rpx)`}]"></view>
			<!-- type -->
			<view 
				v-for="(item,index) in orderTypes"
				:key="index"
				class="select-item"
				:class="{'select-item_active':orderTypeActive===index}"
				@tap="selectOrderType(index)">{{item.tagName}}</view>
		</view>
		<!-- 快递地址 + 门店地址 -->
		<navigator
			:url="orderType=='10'?'/pages/user/pages/address/addressList?source=1':''"
			class="page-panel address-section"
			>
			<!-- 门店地址 -->
			<view 
				v-if="orderType=='15'"
				class="address-content"
				@click.stop="ZZopenLocation(shopDetailInfo.latitude,shopDetailInfo.longitude)">
				<uni-icon
					:color="themeStyles.lightMainColor"
					name="address-full"
					size="60rpx"
				>
				</uni-icon>
				<view class="cen">
					<view class="top">
						<text class="name">{{shopDetailInfo.shopName||"门店地址"}}</text>
					</view>
					<text class="address"
						>{{shopDetailInfo.address||"店主未配置门店地址，无法选择到店。"}}</text
					>
				</view>
				<uni-icon name="right" size="26rpx"> </uni-icon>
			</view>
			<!-- 快递地址 -->
			<view 
				v-if="orderType=='10'"
				class="address-content">
				<uni-icon
					:color="themeStyles.lightMainColor"
					name="address-full"
					size="60rpx"
				>
				</uni-icon>
				<view class="cen">
					<view class="top">
						<text class="name">{{
							addressData.customerName || ""
						}}</text>
						<text class="mobile">{{
							addressData.phone || ""
						}}</text>
					</view>
					<text class="address"
						>{{ addressData.address || ""
						}}{{ addressData.area || "" }}</text
					>
				</view>
				<uni-icon name="right" size="26rpx"> </uni-icon>
			</view>
		</navigator>
		<!-- 商品信息 -->
		<view class="goods-section">
			<view class="goods-list">
				<uni-goods-col
					v-for="(item, index) in orderInfo.orderGoodsList"
					:key="index"
					:goods="item"
					:routeLink="
						`/pages/common/pages/goods/goodsDetail?goodsId=${item.goodsId}`
					"
					:goodsTypeText="item.skuName"
					:goodsPrice="item.priceStr.split('.')"
					:latePrice="item.priceOut"
				>
					<view slot="metaRight">
						<view class="cut-num">x{{ item.buyNumber }}</view>
					</view>
				</uni-goods-col>
			</view>
			<view class="goods-total">
				<text>商品金额：</text>
				<view
					class="goods-total-price"
					:style="themeStyles.textMainColor"
				>
					<text class="price">{{
						orderInfo.goodsPriceTotal[0]
					}}</text>
					<text class="decimal">{{
						orderInfo.goodsPriceTotal[1] || "00"
					}}</text>
				</view>
			</view>
		</view>
		<!-- 明细信息  -->
		<view class="price-section">
			<!-- 金额明细 begin  !buyData.actId不是活动商品 -->
			<view class="yt-list">
				<view
					v-if="!buyData.actId"
					class="df jc-sb yt-list-cell discount"
					@click="toggleCouponListPop(1)"
				>
					<view class="df df-r">
						<text class="cell-tit clamp">优惠券</text>
					</view>
					<template>
						<text
							v-if="orderInfo.couponRemission >= 0"
							class="cell-right"
							>-￥{{ orderInfo.couponRemission || "0" }}</text
						>
						<view v-else class="df jc-c ai-c cell-right"
							><text>选择优惠券</text>
							<uni-icon name="right" size="34rpx"> </uni-icon>
						</view>
					</template>
				</view>
				<!-- v-if="!buyData.actId" -->
				<view  class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">会员</text>
					<text class="cell-right"
						>优惠 ￥{{ orderInfo.memberRemission || "0.00" }}</text
					>
				</view>

				<view
					v-if="orderType=='10'" 
					class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">运费</text>
					<text class="cell-right">{{
						(orderInfo.freightFee && `￥${orderInfo.freightFee}`) ||
							"快递免邮"
					}}</text>
				</view>
			</view>
			<!-- 金额明细 end -->
		</view>

		<!-- 底部 -->
		<view class="footer">
			<view class="footer-box">
				<view class="price-total-box">
					<view class="price-total-name">实付金额：</view>
					<view
						:style="themeStyles.textMainColor"
						class="price-total-content"
					>
						<text class="price">{{ orderInfo.totalFee[0] }}</text>
						<text class="decimal">{{
							orderInfo.totalFee[1] || "00"
						}}</text>
					</view>
				</view>
				<button
					type="primary"
					:style="themeStyles.btnFullColor"
					class="df df-c btn full"
					@click="onSubmitOrder()"
				>
					提交订单
				</button>
			</view>
		</view>

		<!-- 优惠券面板 -->
		<view
			class="coupon-mask"
			:class="maskState === 0 ? 'none' : maskState === 1 ? 'show' : ''"
			@click="toggleCouponListPop(0)"
			>
			<view class="por mask-content" @click.stop.prevent="stopPrevent">
				<view v-if="!couponList.length" class="tac unavailabel-desc"
					>暂无可以使用的优惠券</view
				>
				<!-- 优惠券页面 -->
				<template v-else>
					<view class="coupon-list">
						<view
							@click.stop="selectCoupon(item.couponCustomerId)"
							class="coupon-item"
							v-for="(item, index) in couponList"
							:key="index"
						>
							<view class="con">
								<view class="left">
									<template>
										<text class="title"
											>{{ item.couponTypeValue }}
										</text>
									</template>
									<text class="time"
										>有效期至{{ item.endTime }}</text
									>
								</view>
								<view
									:style="themeStyles.textLightMainColor"
									class="right"
								>
									<view class="price-box">
										<text class="unit"
											>{{
												item.couponType != 30
													? "￥"
													: "%"
											}}
										</text>
										<text class="price">{{
											item.discounts
										}}</text>
									</view>
								</view>
							</view>
							<text class="tips">{{ item.couponName }}</text>
						</view>
					</view>
				</template>
			</view>
			<view class="btn-box">
				<button
					v-if="couponCustomerId && orderInfo.couponRemission"
					:style="themeStyles.btnFullColor"
					@click.stop="selectCoupon(null)"
					class="btn"
				>
					不使用优惠券
				</button>
			</view>
		</view>
		<!-- 提示信息 -->
		<notice
			:visible="showNoStoreAddPop"
			@close="showNoStoreAddPop=false">
				<!-- 标题 -->
            	<template slot="header">
					<view class="zz-mb64">提交失败</view>
            	</template>
				<!-- 内容 -->
            	<template slot="body">
					<view class="zz-flex zz-jc-c lh156 zz-mb64">
						<text 
							:style="themeStyles.textMainColor"
							class="fs156 template__icon template_icon-colse"></text>
					</view>
					<view class="zz-flex zz-jc-c fs26 lh44 color666 zz-mb64">店主暂未配置门店地址无法选择门店</view>
            	</template>
				<!--  -->
            	<template slot="footer">
					<view 
					@click="showNoStoreAddPop=false"
					:style="themeStyles.btnPrimary"
					class="zz-btn zz-btn_large">我知道了</view>
            	</template>
			</notice>
		<!-- 选择支付方式弹层 -->
		<pop-pay
			type="10"
			:showPopPay="showPopPay"
			:orderInfo="orderInfo"
			@close="closePopPay"
			@select-pay-type="selectPayMoneyTypeAfter"
			@payBefore="callPayBefore"
			@payFn="callPay"
			@paySuccessAfter="paySuccessAfter"
			@payFailAfter="payFailAfter"></pop-pay>
	</view>
</template>

<script>
/** api begin */

import { joinGroup } from "@/lib/api/groupServer/group";

import { queryDefaultAddress } from "@/lib/api/customerServer/address";

import { addBargainRecord } from "@/lib/api/bargainServer/initiator";

import { 
	tallyOrder,  //订单结算
	submitOrder  //创建订单
} from "@/lib/api/orderServer/order";
import { queryCanUseCouponList } from "@/lib/api/couponServer/customer";
/** api end */

import { baseFileUri } from "@/utils/request/baseConfig";

/** components begin */
import uniCountdown from "@/components/uniCountdown/uniCountdown";
import uniGoodsCol from "@/components/goods/uniGoodsCol";
import uniIcon from "@/components/uniIcon/uniIcon";
/* 提示弹层 */
import notice from "@/components/notice";
/* 选择支付方式弹层 */
import popPay from "@/components/popPay";
/** components end */
/* mixin begin */
import payMixin from "@/mixins/pay";
import walletMixin from "@/mixins/wallet";
/* mixin end */
import { mapState } from "vuex";
/** 非页面展示数据 begin */
/** 非页面展示数据 end */

export default {
	mixins: [
		payMixin,
		walletMixin
	],
	components: {
		uniCountdown,
		uniGoodsCol,
		uniIcon,
		popPay,
		notice
	},

	data() {
		return {
			/* 20200817 */
			showNoStoreAddPop:false,  //提交订单时---无门店地址时的提示
			/*  */
			buyData: {},
			couponCustomerId: "",
			orderInfo: {
				orderGoodsList: []
			},
			// specDetailId: '',
			// specSkuId: '',
			addressId: "",
			baseFileUri,
			goodsList: [],
			maskState: 0, //优惠券面板显示状态
			showCouponBtn: false,
			couponList: [],
			hasSubmitOrder: false, //订单结算数据
			addressData: {
				customerAddrId: "",
				phone: "",
				address: ""
			}
		};
	},

	computed: {
		...mapState("shop", ["shopDetailInfo"]),
		...mapState("activity", ["activityData"])
	},
	onLoad(option) {
		//console.log("option", option);
		this.buyData = JSON.parse(option.buyData);
		console.log("---商品购买的参数buyData---",this.buyData);
		//商品数据
		// let data = JSON.parse(option.data);
		// console.log(data);
	},

	onShow() {
		//
		if (!this.hasSubmitOrder) {
			this.onTallyOrder();
		}
	},

	methods: {
		//  支付失败之后点击确定
		payFailAfter(){
			let routeLink = "/pages/user/pages/order/orderList";
			uni.reLaunch({ url: routeLink });
		},
		//  支付成功之后点击确定
		paySuccessAfter(){
			//
			let routeLink = "";
			//判断是否是拼团单
			const groupActivity = this.buyData.actType === 10;
			if (!groupActivity) {
				setTimeout(() => {
					routeLink = "/pages/user/pages/order/orderList";
					uni.reLaunch({ url: routeLink });
				}, 300);
			} else {
				setTimeout(() => {
					if (this.activityData.joinActivityId) {
						routeLink = `/pages/activity/pages/group?joinId=${this.activityData.joinActivityId}`;
					} else {
						routeLink = "/pages/activity/pages/myGroup";
					}
					uni.reLaunch({
						url: routeLink
					});
				}, 300);
			}
		},
		//  支付之前
		callPayBefore(val,callback){
			//获取订单id
			callback(this.orderId);
		},
		//  调起支付
		async callPay(val,callback){
			let result;
			this.hasSubmitOrder = true;
			//
			result = await this.onCreateOrder();  //普通订单--直接支付console.log("result",result);
			//支付后
			callback(result);
		},
		// 选择优惠券
		async selectCoupon(couponCustomerId) {
			this.couponCustomerId = couponCustomerId;
			await this.onTallyOrder();
			this.maskState = 0;
		},
		/**
		 * @param { Number } type   // 优惠券列表 1: 显示 0: 隐藏
		 */
		async toggleCouponListPop(type) {
			if (type === 1) {
				this.couponList = await this.getCouponList();
			}
			this.maskState = type;
		},

		// 获取可用优惠券列表
		getCouponList() {
			const buyData = this.buyData;

			const propsData = {
				cartIds: (buyData.cartIds && buyData.cartIds) || "",
				number: buyData.num,
				skuId: buyData.skuId
			};
			return queryCanUseCouponList(propsData).then(res => {
				return res.data;
			});
		},

		// 跳转到商品详情页
		navToOrderProduct(goodsId) {
			uni.navigateTo({
				url: `/pages/common/pages/goods/goodsDetail?goodsId=${goodsId}`
			});
		},

		// 订单结算数据
		async onTallyOrder() {
			/** 地址相关 begin */
			if(this.orderType=='10'){ //线上订单
				try {
					await this.onQueryDefaultAddress();
				} catch (error) {
					console.log("error", error);
					const modalData = {
						content: "请选择您的收货地址",
						showCancel: true
					};
					try {
						await this.$api.showModal(modalData);
						this.navTo(
							`/pages/user/pages/address/addressList?source=${1}`
						);
						return;
					} catch (modelError) {
						/* console.log("modelError", modelError);
						await this.$api.showToast(
							modelError.resultInfo || "出错了，请重试*_*"
						);
						uni.navigateBack(); */
						//切换回“到店”
						this.selectOrderType(0);
						return;
					}
				}
			}
			/** 地址相关 end */

			/** 结算 begin */
			const buyData = this.buyData;
			const propsData = this.processOrderPropsData();
			console.log("propsData", propsData);
			try {
				const res = await tallyOrder(propsData);
				//
				console.log("tallyOrder---",res.data);
				//
				res.data.goodsPriceTotal = `${res.data.goodsPriceTotal}`.split(".");
				this.orderInfo = res.data;

				this.orderInfo.totalFee = `${this.orderInfo.totalFee}`.split(".");
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "操作失败");
				uni.navigateBack();
			}
			/** 结算 end */

			this.loaded = true;
		},

		// 处理结算参数
		processOrderPropsData() {
			const buyData = this.buyData;
			const basePropsData = {
				cartIdList:
					(buyData.cartIds && buyData.cartIds.split(",")) || [],
				//收货地址---
				customerAddrId: this.orderType=='10'?(this.addressData.customerAddrId || ""):"",
				couponCustomerId: this.couponCustomerId || "",
				skuId: buyData.skuId,
				buyNumber: buyData.num,
				type:this.orderType  //10线上订单，15到店自取
			};

			const activityPropsData = {};
			if (buyData.actType !== 0) {
				activityPropsData.activityId = buyData.actId;
				activityPropsData.activityRecordId =
					this.activityData.joinActivityId || "";
				activityPropsData.activityType = buyData.actType;
			}

			// 组合结算活动商品需要的参数
			return Object.assign({}, basePropsData, activityPropsData);
		},

		// 查询默认地址
		onQueryDefaultAddress() {
			if (this.addressData.customerAddrId) return;

			return queryDefaultAddress().then(res => {
				this.addressData = res.data;
			});
		},

		// 提交订单并支付---(普通，拼团，砍价)
		async onSubmitOrder() {
			//  到店 or 快递
			//console.log(this.orderType);
			// 到店
			if(this.orderType==="15"){
				//没有门店地址
				if(!this.shopDetailInfo.address){
					this.showNoStoreAddPop = true;
					return;
				}
			}
			//  快递
			if(this.orderType==="10"){
			}
			//
			/* 
				actType ""普通商品  10拼团  20砍价
			*/
			const hasOrder = this.buyData.actType !== 20;
			/* console.log("this.buyData.actType--",this.buyData.actType);
			console.log(typeof this.buyData.actType);
			console.log(hasOrder);
			return; */
			console.log("this.buyData.actType--",this.buyData.actType);
			console.log(hasOrder);
			try {
				if(this.buyData.actType === 20){  //是砍价订单
					await this.onCreateActiviryRecord();  // 砍价 or 拼团???
				}else{
					//创建订单
					this.orderId = await this.createGeneralOrder();
					//打开支付弹层
					this.openPopPay();
				}
			} catch (error) {
				console.log(error);
				if(error.commonOrder){
					//创建普通订单失败  (普通 + 拼团)
					this.$api.showToast("创建订单失败");
				}
				if(error.bargainOrder){
					//创建砍价订单失败  (普通 + 拼团)
					this.$api.showToast("发起砍价失败");
				}
			}
		},

		// 创建活动记录--发起砍价订单
		async onCreateActiviryRecord() {
			try {
				const joinId = await this.createBargainRecord();
				console.log("---创建砍价记录joinId---",joinId);
				setTimeout(() => {
					uni.reLaunch({
						url: `/pages/activity/pages/bargain?joinId=${joinId}`
					});
				}, 300);
			} catch (error) {
				return Promise.reject({
					bargainOrder:true
				});
				//console.log("error", error);
				//await this.$api.showToast(error.resultInfo || "提交失败 * _ *");
			}
		},

		// 创建砍价记录
		createBargainRecord() {
			const buyData = this.buyData;
			const propsData = {
				bargainId: buyData.actId,
				skuId: buyData.skuId,
				customerAddrId: this.addressData.customerAddrId || "",
				type:this.orderType
			};
			return addBargainRecord(propsData).then(res => {
				return res.data.bargainInitiatorId;
			});
		},

		// 创建订单
		async onCreateOrder() {
			try {
				const payInfo = await this.onPay(this.orderId,this.payMoneyType);
				//console.log("payInfo",payInfo);
				return Promise.resolve(payInfo);
			} catch (error) {
				console.log("error", error);
			}
		},

		// 创建订单
		createGeneralOrder() {
			const propsData = this.processOrderPropsData();
			console.log("propsData", propsData);
			return submitOrder(propsData).then(res => {
				return res.data.orderId;
			}).catch(err=>{
				//普通订单创建失败
				return Promise.reject({
					commonOrder:true
				});
			});
		},

		//显示优惠券面板
		toggleMask(type) {
			let timer = type === "show" ? 10 : 300;
			let state = type === "show" ? 1 : 0;
			this.maskState = 2;
			setTimeout(() => {
				this.maskState = state;
			}, timer);
		},

		numberChange(data) {
			this.number = data.number;
		},

		changePayType(type) {
			this.payType = type;
		},

		stopPrevent() {}
	}
};
</script>

<style lang="scss">
// 订单样式
@import "@/common/styles/order/orderDetail.scss";
/* 订单类型选择 begin */
.zz-ordertype-select {
	position:relative;
	display:flex;
	width:493rpx;
	height:80rpx;
	margin-left:auto;
	margin-right:auto;
	background:$theme-panel-bg-color;
	border-radius:40rpx;
	.select-item {
		position:relative;
		flex:0 0 50%;
		display:flex;
		justify-content:center;
		align-items:center;
		line-height:40rpx;
		font-size:28rpx;
		color:#333;
		z-index:2;
	}
	.select-item_active {
		color:#fff;
	}
	.slider {
		position:absolute;
		top:0;
		left:0;
		width:248rpx;
		height:80rpx;
		border-radius:40rpx;
		border:2px solid rgba(255,255,255,1);
		transition:all .2s ease-in-out;
	}
}
/* 订单类型选择 end */
.container {
	padding-bottom: 120rpx;
}

.goods-section {
	padding-bottom: 20rpx;
}

/* 优惠券面板 begin */
.coupon-mask {
	display: flex;
	justify-content: center;
	align-items: flex-end;
	position: fixed;
	left: 0;
	top: var(--window-top);
	bottom: 0;
	width: 100%;
	background: rgba(0, 0, 0, 0);
	z-index: 9995;
	transition: 0.3s;

	.mask-content {
		width: 100%;
		min-height: 920rpx;
		max-height: 920rpx;
		// padding: 32rpx 24rpx 0;
		padding: 32rpx 0 0;
		border-radius: 16rpx 16rpx 0 0;
		background: $theme-panel-bg-color;
		transform: translateY(100%);
		transition: 0.3s;
		overflow-y: hidden;
	}

	.coupon-list {
		width: 100%;
		padding-bottom: 120rpx;
		min-height: 898rpx;
		max-height: 898rpx;
		overflow-y: scroll;
	}

	.unavailabel-desc {
		margin-top: 40rpx;
		font-weight: blod;
		font-size: $theme-size-large-base;
		color: $theme-color-main-base;
	}

	&.none {
		display: none;
	}

	&.show {
		background: rgba(0, 0, 0, 0.4);

		.mask-content {
			transform: translateY(0);
		}
	}

	.btn-box {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		height: calc(106rpx + var(--safe-area-inset-bottom));
		background-color: $theme-panel-bg-color;
		.btn {
			width: 702rpx;
			height: 80rpx;
			font-weight: 500;
			border-radius: 200rpx;
			font-size: $theme-size-large-base;
		}
	}

	/* 优惠券列表 */
	.coupon-item {
		display: flex;
		flex-direction: column;
		margin: 24rpx 24rpx 0;
		padding: 20rpx 40rpx 16rpx;
		border-radius: 6rpx;
		box-shadow: 0 0 12rpx 0 rgba(240, 240, 240, 1);

		.con {
			display: flex;
			align-items: center;
		}

		.left {
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			flex: 1;
			overflow: hidden;
			height: 100rpx;
		}

		.title {
			font-weight: 500;
			font-size: 32rpx;
			color: $theme-color-main-base;
		}

		.time {
			font-size: $theme-size-small-base;
			color: $theme-color-ghost-base;
			margin-top: 20rpx;
		}

		.right {
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			align-items: center;
			font-size: 26rpx;
			height: 100rpx;
		}

		.price-box {
			justify-content: center;
			.unit {
				font-size: 36rpx;
			}
			.price {
				font-size: 80rpx;
			}
		}

		.tips {
			margin-top: 22rpx;
			font-size: $theme-size-small-base;
			color: $theme-color-base;
			padding-top: 14rpx;
			position: relative;

			&:after {
				position: absolute;
				left: 0;
				top: 0;
				content: "";
				width: 100%;
				height: 0;
				border-bottom: 2rpx dashed #f0f0f0;
				transform: scaleY(50%);
			}
		}
	}
}
/* 优惠券面板 end */
</style>
